<script setup>

import { ref, onMounted } from 'vue'

import { ElMessage, ElMessageBox } from 'element-plus'

import axios from '@/axios'



// 搜索表单

const searchForm = ref({

  name: '',

  type: ''

});



// 数据列表

const subjectList = ref([]);

// 加载状态

const loading = ref(false);

// 对话框显示状态

const dialogVisible = ref(false);



// 修改表单对象以匹配OptionSaveParam

const subjectForm = ref({

  id: null,

  name: '',

  type: '',

  price: null  // 添加价格字段

});



// 修改表单规则

const rules = {

  name: [{ required: true, message: '请输入科目名称', trigger: 'blur' }],

  type: [{ required: true, message: '请输入科室', trigger: 'blur' }],

  price: [{ required: true, message: '请输入价格', trigger: 'blur' }]

};



// 表单引用

const formRef = ref(null);



// 重置搜索

const resetSearch = () => {

  searchForm.value = {

    name: '',

    type: ''

  };

  selectSubjects();

};



// 查询科目列表

const selectSubjects = async () => {

  loading.value = true;

  const token = localStorage.getItem('token');

  if (!token) {

    ElMessage.error('请先登录');

    loading.value = false;

    return;

  }



  try {

    const { data: res } = await axios.get("/admin/option/select", {

      params: searchForm.value,

      headers: {

        'Authorization': token

      }

    });

    if (res.code === 2000) {

      subjectList.value = res.data;

    } else {

      ElMessage.error(res.message || '查询失败');

    }

  } catch (error) {

    if (error.response?.status === 401) {

      ElMessage.error('登录已过期，请重新登录');

    } else {

      ElMessage.error('查询失败：' + error.message);

    }

  } finally {

    loading.value = false;

  }

};



// 打开新增对话框

const handleAdd = () => {

  subjectForm.value = {

    id: null,

    name: '',

    type: '',

    price: null

  };

  dialogVisible.value = true;

};



// 打开编辑对话框

const handleEdit = (row) => {

  subjectForm.value = {

    id: row.id,

    name: row.name,

    type: row.type,

    price: row.price ? Number(row.price) : null

  };

  dialogVisible.value = true;

};



// 删除科目

const handleDelete = async (id) => {

  const token = localStorage.getItem('token');

  if (!token) {

    ElMessage.error('请先登录');

    return;

  }



  try {

    await ElMessageBox.confirm('确认删除该科目吗？', '提示', {

      type: 'warning'

    });

    const { data: res } = await axios.post(`/admin/option/delete/${id}`, null, {

      headers: {

        'Authorization': token

      }

    });

    if (res.code === 2000) {

      ElMessage.success('删除成功');

      selectSubjects();

    } else {

      ElMessage.error(res.message || '删除失败');

    }

  } catch (error) {

    if (error !== 'cancel') {

      ElMessage.error('删除失败：' + error.message);

    }

  }

};



// 提交表单

const submitForm = async () => {

  if (!formRef.value) return;

  

  const token = localStorage.getItem('token');

  if (!token) {

    ElMessage.error('请先登录');

    return;

  }



  try {

    await formRef.value.validate();

    

    // 处理提交数据

    const submitData = {

      ...subjectForm.value,

      price: subjectForm.value.price ? Number(subjectForm.value.price) : 0

    };



    const { data: res } = await axios.post('/admin/option/save', submitData, {

      headers: {

        'Authorization': token,

        'Content-Type': 'application/json'

      }

    });

    

    if (res.code === 2000) {

      ElMessage.success(subjectForm.value.id ? '更新成功' : '新增成功');

      dialogVisible.value = false;

      selectSubjects();

    } else {

      ElMessage.error(res.message || (subjectForm.value.id ? '更新失败' : '新增失败'));

    }

  } catch (error) {

    if (error.response?.status === 401) {

      ElMessage.error('登录已过期，请重新登录');

    } else {

      ElMessage.error('操作失败：' + error.message);

    }

  }

};



onMounted(() => {

  selectSubjects();

});

</script>



<template>

  <div style="background-color:#fff;padding:10px 20px;">

    <span style="line-height:60px;font-size:20px;">科目管理</span>

  </div>

  

  <!-- 科目数据搜索卡片 -->

  <el-card style="margin:20px;height: 100px;">

    <el-form :inline="true">

      <el-form-item label="科目名称">

        <el-input placeholder="请输入" style="width:220px;" v-model="searchForm.name"

                  @keydown.enter="selectSubjects"></el-input>

      </el-form-item>

      <el-form-item label="科室">

        <el-input placeholder="请输入" style="width:220px;" v-model="searchForm.type"

                  @keydown.enter="selectSubjects"></el-input>

      </el-form-item>

      <el-form-item>

        <el-button type="primary" @click="selectSubjects">搜索</el-button>

        <el-button @click="resetSearch">重置</el-button>

        <el-button type="success" @click="handleAdd">新增科目</el-button>

      </el-form-item>

    </el-form>

  </el-card>



  <!-- 科目数据展示 -->

  <el-card style="margin:20px;">

    <el-table 

      v-loading="loading"

      :data="subjectList" 

      border 

      stripe 

      style="width: 100%"

    >

      <el-table-column prop="id" label="ID" width="80"></el-table-column>

      <el-table-column prop="name" label="科目名称" width="180"></el-table-column>

      <el-table-column prop="type" label="科室" width="180"></el-table-column>

      <el-table-column prop="price" label="价格" width="180">

        <template #default="scope">

          {{ scope.row.price ? `￥${scope.row.price}` : '-' }}

        </template>

      </el-table-column>

      <el-table-column label="操作" width="180">

        <template #default="scope">

          <el-button type="primary" @click="handleEdit(scope.row)">编辑</el-button>

          <el-button type="danger" @click="handleDelete(scope.row.id)">删除</el-button>

        </template>

      </el-table-column>

    </el-table>

  </el-card>



  <!-- 新增/编辑对话框 -->

  <el-dialog :title="subjectForm.id ? '编辑科目' : '新增科目'" v-model="dialogVisible" width="50%">

    <el-form 

      ref="formRef"

      :model="subjectForm" 

      :rules="rules" 

      label-width="100px"

    >

      <el-form-item label="科目名称" prop="name">

        <el-input v-model="subjectForm.name" placeholder="请输入科目名称"></el-input>

      </el-form-item>

      <el-form-item label="科室" prop="type">

        <el-input v-model="subjectForm.type" placeholder="请输入科室"></el-input>

      </el-form-item>

      <el-form-item label="价格" prop="price">

        <el-input-number 

          v-model="subjectForm.price"

          :precision="2"

          :step="0.1"

          :min="0"

          :max="999999.99"

          style="width: 100%"

          placeholder="请输入价格"

        ></el-input-number>

      </el-form-item>

    </el-form>

    <template #footer>

      <span class="dialog-footer">

        <el-button @click="dialogVisible = false">取消</el-button>

        <el-button type="primary" @click="submitForm">确定</el-button>

      </span>

    </template>

  </el-dialog>

</template>



<style scoped>

.el-card {

  margin: 20px;

}



.el-form {

  margin-top: 20px;

}



.dialog-footer {

  text-align: right;

  margin-top: 20px;

}

</style>
